<script>
//导入共通组件
import Footer from '../components/Footer.vue';
import  axios from 'axios';
export default {
  name: 'Index',
  data() {
    return {
      businesses: [],
      userPermissions: [], // 存储用户权限
      isDeleteModalVisible: false,     // 控制弹窗是否显示
      shopIdToDelete: null,            // 用户要删除的店铺ID
      deleteMessage: null,             // 删除结果提示
      deleteMessageType: ''            // 'success' 或 'error'
    }
  },
  mounted() {
    this.handleScroll = ()=>{
      let s1=document.documentElement.scrollTop;
      let s2=document.body.scrollTop;
      let scroll= s1==0 ?s2:s1;
      let width=document.documentElement.clientWidth;
      let search=this.$refs.fixedBox;
      if(scroll>width*0.12){
        search.style.position="fixed";
        search.style.left='0';
        search.style.top='0';
      }else{
        search.style.position="static";
      }
    };
    document.addEventListener('scroll', this.handleScroll);

    // 获取并解析JWT，判断用户权限
    this.parseJWT();

    // 发送GET请求获取商家列表
    this.fetchBusinesses();
  },
  beforeUnmount() {
    document.removeEventListener('scroll', this.handleScroll);
  },
  components: {
    Footer
  },
  methods: {
    // 打开删除店铺弹窗
    openDeleteModal() {
      this.isDeleteModalVisible = true;
      this.shopIdToDelete = null;      // 清空输入
      this.deleteMessage = null;       // 清空提示
    },
    // 关闭删除店铺弹窗
    closeDeleteModal() {
      this.isDeleteModalVisible = false;
      this.shopIdToDelete = null;
      this.deleteMessage = null;
    },// 确认删除店铺
    async confirmDeleteShop() {
      // 校验输入
      if (!this.shopIdToDelete || isNaN(this.shopIdToDelete) || this.shopIdToDelete <= 0) {
        this.deleteMessage = { type: 'error', text: '请输入有效的店铺ID（大于0的数字）' };
        return;
      }

      const shopId = Number(this.shopIdToDelete);

      try {
        const token = sessionStorage.getItem('jwt');
        if (!token) {
          this.deleteMessage = { type: 'error', text: '用户未登录，无法删除！' };
          return;
        }

        // 发送 DELETE 请求到后端
        const response = await axios.delete(`/businesses/${shopId}`, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token.slice(1,-1)}`  // 添加认证令牌
          }
        });

        if (response.status === 200 || response.status === 204) {
          this.deleteMessage = { type: 'success', text: '店铺删除成功！' };
          await this.fetchBusinesses();
        } else {
          // 后端返回错误信息
          this.deleteMessage = {
            type: 'error',
            text: response.data?.message || '删除失败，请重试'
          };
        }
      } catch (err) {
        console.error('删除店铺失败:', err);
        if (err.response) {
          this.deleteMessage = {
            type: 'error',
            text: err.response.data?.message || `删除失败 (${err.response.status})`
          };
        } else if (err.request) {
          this.deleteMessage = { type: 'error', text: '网络错误，请检查连接！' };
        } else {
          this.deleteMessage = { type: 'error', text: '删除失败，请重试！' };
        }
      } finally {
        // 3秒后自动关闭弹窗 & 清除提示（可选）
        setTimeout(() => {
          this.closeDeleteModal();
        }, 3000);
      }
    },
    // 解析JWT token（使用你提供的解析逻辑）
    parseJWT() {
      const token = sessionStorage.getItem('jwt');
      if (token) {
        try {
          const payload = token.split('.')[1];
          const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
          const decodedPayload = JSON.parse(atob(base64));

          // 获取权限信息
          const authString = decodedPayload.auth || '';
          const authorities = authString.split(',');

          // 设置用户权限数组
          this.userPermissions = authorities;

        } catch (error) {
          console.error('解析JWT失败:', error);
          this.userPermissions = [];
        }
      } else {
        this.userPermissions = [];
      }
    },

    // 判断是否有指定权限
    hasPermission(permission) {
      return this.userPermissions.includes(permission);
    },

    // 获取最高权限（优先ADMIN）
    getHighestPermission() {
      if (this.hasPermission('ADMIN')) {
        return 'ADMIN';
      }
      if (this.hasPermission('BUSINESS')) {
        return 'BUSINESS';
      }
      return null;
    },

    toBusinessList(orderTypeId){
      this.$router.push({path:'/businessList',query:{orderTypeId:orderTypeId}});
    },

    // 新增用户
    toAddUser() {
      this.$router.push({ path: '/addPerson' });
    },

    // 新增店铺
    toAddShop() {
      this.$router.push({ path: '/addShop' });
    },

    // 新增商品
    toAddProduct() {
      this.$router.push({ path: '/addProduct' });
    },

    // 查看订单
    toViewOrders() {
      this.$router.push({ path: '/orderList' });
    },

    toUpdateShop() {
      this.$router.push({ path: '/updateShop' });
    },

    toUpdateProduct() {
      this.$router.push({ path: '/updateProduct' });
    },

    // 发送GET请求获取商家列表
    async fetchBusinesses() {
      try {
        const token = sessionStorage.getItem('jwt');
        if(token === null)return;
        const response = await axios.get('/businesses',{
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token.slice(1,-1)}`  // 添加认证令牌
          }
        });
        this.businesses = response.data;
      } catch (error) {
        console.error('获取商家列表失败:', error);
      }
    },

    // 跳转到商家详情页
    goToBusinessInfo(businessId) {
      this.$router.push({ path: '/businessInfo', query: { businessId: businessId } });
    }
  }
}
</script>

<template>
  <div class="wrapper">
    <!--header部分-->
    <header>
      <div class="icon-location-box">
        <div class="icon-location"></div>
      </div>
      <div class="location-text">沈阳市规划大厦<i class="fa fa-caret-down"></i></div>
    </header>

    <!--search部分-->
    <div class="search">
      <!--不直接把外面这个div固定，是为了在脱离文档流的时候仍然把原本的位置占住，否则会整体向上跳-->
      <div class="search-fixed-top" ref="fixedBox"><!--固定在头部-->
        <div class="search-box">
          <i class="fa fa-search"></i>搜索饿了么商家、商品名称
        </div>
      </div>
    </div>

    <!-- 权限控制按钮区域 -->
    <div v-if="getHighestPermission()" class="permission-buttons">
      <!-- ADMIN权限（最高优先级） -->
      <div v-if="getHighestPermission() === 'ADMIN'" class="admin-buttons">
        <button @click="toAddUser" class="permission-btn admin-btn">新增用户</button>
        <button @click="toAddShop" class="permission-btn admin-btn">新增店铺</button>
        <button @click="openDeleteModal" class="permission-btn admin-btn">删除店铺</button>
      </div>

      <!-- BUSINESS权限 -->
      <div v-if="getHighestPermission() === 'BUSINESS'" class="business-buttons">
        <button @click="toAddProduct" class="permission-btn business-btn">新增商品</button>
        <button @click="toViewOrders" class="permission-btn business-btn">查看订单</button>
        <button @click="toUpdateShop" class="permission-btn business-btn">修改商家</button>
        <button @click="toUpdateProduct" class="permission-btn business-btn">修改食品</button>
      </div>
    </div>

    <!--点餐分类部分-->
    <ul class="foodtype">
      <li @click="toBusinessList(1)">
        <img src="../assets/dcfl01.png" alt="" />
        <p>美食</p>
      </li>
      <li @click="toBusinessList(2)">
        <img src="../assets/dcfl02.png" alt="" />
        <p>早餐</p>
      </li>
      <li @click="toBusinessList(3)">
        <img src="../assets/dcfl03.png" alt="" />
        <p>跑腿代购</p>
      </li>
      <li @click="toBusinessList(4)">
        <img src="../assets/dcfl04.png" alt="" />
        <p>汉堡披萨</p>
      </li>
      <li @click="toBusinessList(5)">
        <img src="../assets/dcfl05.png" alt="" />
        <p>甜品饮品</p>
      </li>
      <li @click="toBusinessList(6)">
        <img src="../assets/dcfl06.png" alt="" />
        <p>速食简餐</p>
      </li>
      <li @click="toBusinessList(7)">
        <img src="../assets/dcfl07.png" alt="" />
        <p>地方小吃</p>
      </li>
      <li @click="toBusinessList(8)">
        <img src="../assets/dcfl08.png" alt="" />
        <p>米粉面馆</p>
      </li>
      <li @click="toBusinessList(9)">
        <img src="../assets/dcfl09.png" alt="" />
        <p>包子粥铺</p>
      </li>
      <li @click="toBusinessList(10)">
        <img src="../assets/dcfl10.png" alt="" />
        <p>炸鸡炸串</p>
      </li>
    </ul>

    <!--横幅广告部分-->
    <div class="banner">
      <h3>品质套餐</h3>
      <p>搭配齐全吃得好</p>
      <a href="">立即抢购 &gt;</a>
    </div>

    <!--超级会员部分-->
    <div class="supermember">
      <div class="left">
        <img src="img/king.png" alt="" />
        <h3>超级会员</h3>
        <p>&#8226; 每月享超值权益</p>
      </div>
      <div class="right">
        立即开通 &gt;
      </div>
    </div>

    <!--推荐商家部分-->
    <div class="recommend">
      <div class="recommend-line"></div>
      <p>推荐商家</p>
      <div class="recommend-line"></div>
    </div>

    <!--推荐方式部分-->
    <ul class="recommendtype">
      <li>综合排序<i class="fa fa-caret-down"></i></li>
      <li>距离最近</li>
      <li>销量最高</li>
      <li>筛选<i class="fa fa-filter"></i></li>
    </ul>

    <!--推荐商家列表部分-->
    <ul class="business">
      <li v-for="business in businesses.data" :key="business.id" @click="goToBusinessInfo(business.id)">
        <img :src="business.businessImg" alt="" />
        <div class="business-info">
          <div class="business-info-h">
            <h3>{{ business.businessName }}</h3>
            <div class="business-info-like">&#8226;</div>
          </div>
          <div class="business-info-star">
            <div class="business-info-star-left">
              <i class="fa fa-star"></i>
              <i class="fa fa-star"></i>
              <i class="fa fa-star"></i>
              <i class="fa fa-star"></i>
              <i class="fa fa-star"></i>
              <p>{{ business.businessExplain }} 月售100+单</p>
            </div>
            <div class="business-info-star-right">
              蜂鸟专送
            </div>
          </div>
          <div class="business-info-delivery">
            <p>¥{{ business.startPrice }}起送 | ¥{{ business.deliveryPrice }}配送</p>
            <p>4.7公里 | 35分钟</p>
          </div>
          <div class="business-info-explain">
            <div>{{ business.remarks }}</div>
          </div>
          <div class="business-info-promotion">
            <div class="business-info-promotion-left">
              <div class="business-info-promotion-left-incon">新</div>
              <p>饿了么新用户首单立减9元</p>
            </div>
            <div class="business-info-promotion-right">
              <p>2个活动</p>
              <i class="fa fa-caret-down"></i>
            </div>
          </div>
          <div class="business-info-promotion">
            <div class="business-info-promotion-left">
              <div class="business-info-promotion-left-incon" style="background-color: #F1884F;">特</div>
              <p>特价商品5元起</p>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!-- 删除店铺弹窗 -->
    <div v-if="isDeleteModalVisible" class="modal-overlay">
      <div class="modal-box">
        <h3>删除店铺</h3>
        <p>请输入要删除的店铺编号（ID）：</p>
        <input
            type="number"
            v-model.number="shopIdToDelete"
            placeholder="店铺ID"
            class="modal-input"
        />
        <!-- 提示消息 -->
        <p v-if="deleteMessage" :class="['modal-message', deleteMessage.type]">
          {{ deleteMessage.text }}
        </p>
        <!-- 按钮组 -->
        <div class="modal-buttons">
          <button @click="confirmDeleteShop" class="modal-confirm-btn">确认删除</button>
          <button @click="closeDeleteModal" class="modal-cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <!--底部菜单部分-->
    <Footer></Footer>
  </div>
</template>

<style scoped>
/*总容器*/
.wrapper{
  width: 100%;
  height: 100%;
}

/*header*/
.wrapper header{
  width: 100%;
  height: 12vw;
  background-color: #0097FF;

  display: flex;
  align-items: center;
}
.wrapper header .icon-location-box{
  width: 3.5vw;
  height: 3.5vw;
  margin: 0 1vw 0 3vw;
}
.wrapper header .location-text{
  font-size: 4.5vw;
  font-weight: 700;
  color: #fff;
}
.wrapper header .location-text .fa-caret-down{
  margin: 1vw;
}

/*search*/
.wrapper .search{
  width: 100%;
  height: 13vw;
}
.wrapper .search .search-fixed-top{
  width: 100%;
  height: 13vw;
  background-color: #0097FF;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .search .search-fixed-top .search-box{
  /*做白框*/
  width: 90%;
  height: 9vw;
  background-color: #fff;
  border-radius: 2px;
  /*弹性布局*/
  display: flex;
  justify-content: center;
  align-items: center;
  /*字体*/
  font-size: 3.5vw;
  color: #AEAEAE;
  font-family: "宋体";
  /*取消文本选中效果，即鼠标光标在上面还是鼠标光标，此样式让文本选中状态无效*/
  user-select: none;
}
.wrapper .search .search-fixed-top .search-box .fa-search{
  margin-right: 1vw;
}

/* 权限控制按钮样式 */
.permission-buttons {
  width: 100%;
  padding: 2vw;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.admin-buttons,
.business-buttons {
  display: flex;
  gap: 2vw;
  justify-content: center;
  flex-wrap: wrap;
}

.permission-btn {
  padding: 1.5vw 2.5vw;
  border: none;
  border-radius: 4px;
  font-size: 3.2vw;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 20vw;
}

.admin-btn {
  background-color: #007bff;
  color: white;
}

.admin-btn:hover {
  background-color: #0056b3;
  transform: translateY(-1px);
}

.business-btn {
  background-color: #28a745;
  color: white;
}

.business-btn:hover {
  background-color: #1e7e34;
  transform: translateY(-1px);
}

/*点餐分类部分*/
.wrapper .foodtype{
  width: 100%;
  height: 48vw;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-content: center;
}
.wrapper .foodtype li{
  width: 18vw;
  height: 20vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  user-select: none;
  cursor: pointer;
}
.wrapper .foodtype li img{
  width: 12vw;
  height: 12vw;
}
.wrapper .foodtype li p{
  font-size: 3.2vw;
  color: #666;
}

/*横幅广告部分*/
.wrapper .banner{
  width: 95%;
  margin: 0 auto;
  height: 29vw;
  /*让背景图片自适应整个容器，就用下面三行样式*/
  background-image: url(../assets/index_banner.png);
  background-repeat: no-repeat;
  background-size: cover;

  box-sizing: border-box;
  padding: 2vw 6vw;
}
.wrapper .banner h3{
  font-size:  4.2vw;
  margin-bottom: 1.2vw;
}
.wrapper .banner p{
  font-size: 3.4vw;
  color: #666;
  margin-bottom: 2.4vw;
}
.wrapper .banner a{
  font-size: 3vw;
  color: #C79060;
  font-weight: 700;
}

/*超级会员部分*/
.wrapper .supermember{
  width: 95vw;
  margin: 0 auto;
  height: 11.5vw;
  background-color: #FEEDC1;
  margin-top: 1.3vw;
  border-radius: 2px;
  color: #644F1B;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .supermember .left{
  display: flex;
  align-items: center;
  margin-left: 4vw;
  user-select: none;
}
.wrapper .supermember .left img{
  width: 6vw;
  height: 6vw;
  margin-right: 2vw;
}
.wrapper .supermember .left h3{
  font-size: 4vw;
  margin-right: 2vw;
}
.wrapper .supermember .left p{
  font-size: 3vw;
}
.wrapper .supermember .right{
  font-size: 3vw;
  margin-right: 4vw;
  cursor: pointer;
}

/*推荐商家部分*/
.wrapper .recommend{
  width: 100%;
  height: 14vw;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .recommend .recommend-line{
  width: 6vw;
  height: 0.2vw;
  background-color: #888;
}
.wrapper .recommend p{
  font-size: 4vw;
  margin: 0 4vw;
}

/*推荐方式部分*/
.wrapper .recommendtype{
  width: 100%;
  height: 5vw;
  margin-bottom: 5vw;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.wrapper .recommendtype li{
  font-size: 3.5vw;
  color: #555;
}

/*推荐商家列表部分*/
.wrapper .business{
  width: 100%;
  padding-bottom: 14vw;
  margin-bottom: 14vw;/*不知道为什么设置margin没用，设置padding有用*/
}
.wrapper .business li{
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;
  border-bottom: solid 1px #DDD;
  display: flex;
}
.wrapper .business li img{
  width: 18vw;
  height: 18vw;
}
.wrapper .business li .business-info{
  width: 100%;
  box-sizing: border-box;
  padding-left: 3vw;
}
.wrapper .business li .business-info .business-info-h{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
}
.wrapper .business li .business-info .business-info-h h3{
  font-size: 4vw;
  color: #333;
}
.wrapper .business li .business-info .business-info-h .business-info-like{
  width: 1.6vw;
  height: 3.4vw;
  background-color: #666;
  color: #fff;
  font-size: 4vw;
  margin-right: 4vw;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .business li .business-info .business-info-star{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  font-size: 3.1vw;
}
.wrapper .business li .business-info .business-info-star .business-info-star-left{
  display: flex;
  align-items: center;
}
.wrapper .business li .business-info .business-info-star .business-info-star-left .fa-star{
  color: #FEC80E;
  margin-right: 0.5vw;
}
.wrapper .business li .business-info .business-info-star .business-info-star-left p{
  color: #666;
  margin-left: 1vw;
}
.wrapper .business li .business-info .business-info-star .business-info-star-right{
  background-color: #0097FF;
  color: #fff;
  font-size: 2.4vw;
  border-radius: 2px;
  padding: 0 0.6vw;
}
.wrapper .business li .business-info .business-info-delivery{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  color: #666;
  font-size: 3.1vw;
}
.wrapper .business li .business-info .business-info-explain{
  display: flex;
  align-items: center;
  margin-bottom: 3vw;
}
.wrapper .business li .business-info .business-info-explain div{
  border: solid 1px #DDD;
  font-size: 2.8vw;
  color: #666;
  border-radius: 3px;
  padding: 0 0.1vw;
}
.wrapper .business li .business-info .business-info-promotion{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.8vw;
}
.wrapper .business li .business-info .business-info-promotion .business-info-promotion-left{
  display: flex;
  align-items: center;
}
.wrapper .business li .business-info .business-info-promotion .business-info-promotion-left .business-info-promotion-left-incon{
  width: 4vw;
  height: 4vw;
  background-color: #70BC46;
  border-radius: 3px;
  font-size: 3vw;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .business li .business-info .business-info-promotion .business-info-promotion-left p{
  color: #666;
  font-size: 3vw;
  margin-left: 2vw;
}
.wrapper .business li .business-info .business-info-promotion .business-info-promotion-right{
  display: flex;
  align-items: center;
  font-size: 2.5vw;
  color: #999;
}
.wrapper .business li .business-info .business-info-promotion .business-info-promotion-right p{
  margin-right: 2vw;
}

/* 弹窗遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

/* 弹窗内容框 */
.modal-box {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  min-width: 320px;
  text-align: center;
}

.modal-box h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
}

.modal-box p {
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
}

.modal-input {
  width: 100%;
  padding: 8px 12px;
  margin-bottom: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.modal-message {
  margin-bottom: 16px;
  font-size: 14px;
  font-weight: bold;
}

.modal-message.success {
  color: #1a7324;
}

.modal-message.error {
  color: #c62828;
}

.modal-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.modal-confirm-btn {
  padding: 8px 16px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.modal-confirm-btn:hover {
  background-color: #c82333;
}

.modal-cancel-btn {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.modal-cancel-btn:hover {
  background-color: #5a6268;
}

</style>